{% extends "base.html" %}

{% block content %}
<div class="max-w-4xl mx-auto">
    <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">Edit Document</h1>
        <p class="text-gray-600">Update document metadata and information</p>
    </div>

    <div id="errorSummary" class="hidden mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
        <div class="flex items-start space-x-3">
            <i class="fas fa-exclamation-triangle text-red-600 text-xl mt-1"></i>
            <div class="flex-1">
                <p class="font-medium text-red-900">Please correct the following errors:</p>
                <ul id="errorList" class="mt-2 text-sm text-red-700 list-disc list-inside"></ul>
            </div>
        </div>
    </div>

    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
        <div class="flex items-center space-x-3">
            <i class="fas fa-file text-blue-600 text-xl"></i>
            <div>
                <p class="font-medium text-blue-900" id="currentFileName">Loading...</p>
                <p class="text-sm text-blue-700">Original file: <span id="originalFileName"></span></p>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <form id="editForm">
            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">File Name <span class="text-red-500">*</span></label>
                <input 
                    type="text" 
                    name="file_name"
                    id="fileNameInput"
                    placeholder="Enter file name"
                    maxlength="128"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    required
                >
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Country/Region <span class="text-red-500">*</span></label>
                    <select 
                        name="country"
                        id="countrySelect"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Country</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Document Type <span class="text-red-500">*</span></label>
                    <select 
                        name="document_type"
                        id="documentType"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Type</option>
                        <option value="pdf">PDF</option>
                        <option value="doc">DOC</option>
                        <option value="docx">DOCX</option>
                        <option value="xlsx">XLSX</option>
                        <option value="txt">TXT</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Regulation ID</label>
                    <input 
                        type="text" 
                        name="regulation_id"
                        id="regulationId"
                        maxlength="64"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    >
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Issuing Authority <span class="text-red-500">*</span></label>
                    <input 
                        type="text" 
                        name="issuing_authority"
                        id="issuingAuthority"
                        maxlength="64"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Collection <span class="text-red-500">*</span></label>
                    <select 
                        name="collection"
                        id="collectionSelect"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Collection</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Status <span class="text-red-500">*</span></label>
                    <select 
                        name="status"
                        id="statusSelect"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                        <option value="">Select Status</option>
                        <option value="Draft">Draft</option>
                        <option value="Effective">Effective</option>
                        <option value="Expired">Expired</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Effective Date <span class="text-red-500">*</span></label>
                    <input 
                        type="date" 
                        name="effective_date"
                        id="effectiveDate"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        required
                    >
                    <p id="effectiveDateError" class="hidden mt-2 text-sm text-red-600"></p>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Version</label>
                    <input 
                        type="text" 
                        name="version"
                        id="version"
                        maxlength="32"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    >
                </div>
            </div>

            <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">Tags</label>
                <div class="relative">
                    <input 
                        type="text" 
                        id="tagInput"
                        placeholder="Type and press Enter to add tags"
                        maxlength="32"
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                        autocomplete="off"
                    >
                    <input type="hidden" name="tags" id="tagsHidden">
                    <div id="tagSuggestions" class="hidden absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg max-h-48 overflow-y-auto"></div>
                </div>
                <div id="tagContainer" class="mt-2 flex flex-wrap gap-2"></div>
                <p class="mt-1 text-sm text-gray-500">Press Enter to add tags. Maximum 8 tags allowed.</p>
            </div>

            <div class="flex items-center justify-end space-x-4">
                <button 
                    type="button"
                    onclick="location.href='/documents'"
                    class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
                >
                    Cancel
                </button>
                <button 
                    type="submit"
                    class="px-6 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 flex items-center space-x-2"
                    id="submitButton"
                >
                    <i class="fas fa-save"></i>
                    <span>Save Changes</span>
                </button>
            </div>
        </form>
    </div>

    <div id="saveStatus" class="hidden mt-6"></div>
</div>
{% endblock %}

{% block scripts %}
<script>
let selectedTags = [];
const MAX_TAGS = 8;
const TAG_COLORS = ['bg-blue-100 text-blue-800', 'bg-green-100 text-green-800', 'bg-purple-100 text-purple-800'];
const currentDocId = '{{ doc_id }}';

document.addEventListener('DOMContentLoaded', async () => {
    await loadCountries();
    await loadCollections();
    await loadDocumentData();
});

async function loadCountries() {
    const response = await fetch('/api/countries');
    const data = await response.json();
    if (data.status === 'success') {
        const select = document.getElementById('countrySelect');
        data.countries.forEach(country => {
            const option = document.createElement('option');
            option.value = country.name;
            option.textContent = country.name;
            select.appendChild(option);
        });
    }
}

async function loadCollections() {
    const response = await fetch('/api/collections/list');
    const data = await response.json();
    if (data.status === 'success') {
        const select = document.getElementById('collectionSelect');
        data.collections.forEach(collection => {
            const option = document.createElement('option');
            option.value = collection.name;
            option.textContent = collection.display_name || collection.name;
            select.appendChild(option);
        });
    }
}

async function loadDocumentData() {
    try {
        const response = await fetch(`/api/documents/${currentDocId}/metadata`);
        const data = await response.json();
        
        if (data.status === 'success') {
            const doc = data.document;
            document.getElementById('currentFileName').textContent = doc.file_name || doc.filename;
            document.getElementById('originalFileName').textContent = doc.filename;
            document.getElementById('fileNameInput').value = doc.file_name || '';
            document.getElementById('countrySelect').value = doc.country || '';
            document.getElementById('documentType').value = doc.document_type || '';
            document.getElementById('regulationId').value = doc.regulation_id || '';
            document.getElementById('issuingAuthority').value = doc.issuing_authority || '';
            document.getElementById('collectionSelect').value = doc.collection || '';
            document.getElementById('statusSelect').value = doc.status || 'Draft';
            document.getElementById('effectiveDate').value = doc.effective_date || '';
            document.getElementById('version').value = doc.version || '';
            
            if (doc.tags && Array.isArray(doc.tags)) {
                selectedTags = [...doc.tags];
                renderTags();
            }
        }
    } catch (error) {
        console.error('Error loading document:', error);
        alert('Failed to load document data');
    }
}

const tagInput = document.getElementById('tagInput');

tagInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        e.preventDefault();
        const tag = tagInput.value.trim();
        if (tag) addTag(tag);
    }
});

function addTag(tag) {
    if (selectedTags.length >= MAX_TAGS || selectedTags.includes(tag)) return;
    const tagPattern = /^[A-Za-z0-9]+$/;
    if (!tagPattern.test(tag) || tag.length > 32) return;
    
    selectedTags.push(tag);
    renderTags();
    tagInput.value = '';
}

function removeTag(tag) {
    selectedTags = selectedTags.filter(t => t !== tag);
    renderTags();
}

function renderTags() {
    const container = document.getElementById('tagContainer');
    container.innerHTML = '';
    selectedTags.forEach((tag, index) => {
        const colorClass = TAG_COLORS[index % TAG_COLORS.length];
        const tagEl = document.createElement('span');
        tagEl.className = `inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${colorClass}`;
        tagEl.innerHTML = `${tag}<button type="button" onclick="removeTag('${tag}')" class="ml-2 focus:outline-none"><i class="fas fa-times text-xs"></i></button>`;
        container.appendChild(tagEl);
    });
}

document.getElementById('editForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const formData = {
        file_name: document.getElementById('fileNameInput').value.trim(),
        country: document.getElementById('countrySelect').value,
        document_type: document.getElementById('documentType').value,
        regulation_id: document.getElementById('regulationId').value.trim(),
        issuing_authority: document.getElementById('issuingAuthority').value.trim(),
        effective_date: document.getElementById('effectiveDate').value.trim(),
        version: document.getElementById('version').value.trim(),
        collection: document.getElementById('collectionSelect').value,
        status: document.getElementById('statusSelect').value,
        tags: selectedTags
    };
    
    const submitButton = document.getElementById('submitButton');
    const saveStatus = document.getElementById('saveStatus');
    
    submitButton.disabled = true;
    submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i><span>Saving...</span>';
    saveStatus.classList.remove('hidden');
    saveStatus.innerHTML = `
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div class="flex items-center space-x-3">
                <i class="fas fa-spinner fa-spin text-blue-600 text-xl"></i>
                <div><p class="font-medium text-blue-900">Saving Changes</p></div>
            </div>
        </div>
    `;
    
    try {
        const response = await fetch(`/api/documents/${currentDocId}`, {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(formData)
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            saveStatus.innerHTML = `
                <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                    <div class="flex items-center space-x-3">
                        <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        <div><p class="font-medium text-green-900">Document Updated Successfully</p></div>
                    </div>
                </div>
            `;
            setTimeout(() => location.href = '/documents', 2000);
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        saveStatus.innerHTML = `
            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                <div class="flex items-center space-x-3">
                    <i class="fas fa-times-circle text-red-600 text-xl"></i>
                    <div><p class="font-medium text-red-900">Update Failed</p><p class="text-sm text-red-700">${error.message}</p></div>
                </div>
            </div>
        `;
        submitButton.disabled = false;
        submitButton.innerHTML = '<i class="fas fa-save"></i><span>Save Changes</span>';
    }
});
</script>
{% endblock %}